﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Web.Configuration;
using System.IO; 

namespace YuuzleComic.Common
{
    public class XindmSession
    {
        public static CookieContainer cookies = new CookieContainer();

        public static void setCookie(string url)
        {
            if (cookies == null || cookies.Count == 0)
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
                myHttpWebRequest.Timeout = 20 * 1000; //连接超时
                myHttpWebRequest.Accept = "*/*";
                myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)";
                myHttpWebRequest.CookieContainer = new CookieContainer(); //暂存到新实例
                myHttpWebRequest.GetResponse().Close();
                cookies = myHttpWebRequest.CookieContainer; //保存cookies
            }
        }

        public static void saveImage(string imgUrl,string imgPath)
        {
            if (imgUrl.Contains("xindm.cn"))
            {
                string host = "http://" + new Uri(imgUrl).Host + "/";
                XindmSession.setCookie(host);
            }
            HttpWebRequest myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(imgUrl);//moviePath为图片的真实URL  
            myHttpWebRequest.Referer = "http://"+ new Uri(imgUrl).Host +"/";//伪造网址
            myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)";
            myHttpWebRequest.CookieContainer = cookies;
            System.Net.HttpWebResponse response = myHttpWebRequest.GetResponse() as System.Net.HttpWebResponse;
            System.IO.Stream responseStream = response.GetResponseStream();
            System.Drawing.Image img = System.Drawing.Image.FromStream(responseStream);
            img.Save(imgPath);//保存到硬盘
            responseStream.Close();
            response.Close();  
        }

    }
}
